<template>
  <!-- 头部信息 -->
  <HeaderView :title="route.query.type ==='add' ? '新增地址' : '修改地址'" :hasBack='true' path="address"/>

  <div class="address">
    <van-address-edit
    :area-list="areaList"
    :address-info="addressDetail"
    show-delete
    show-set-default
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    :save-button-text="route.query.type === 'add' ? '保存' : '修改'"
    @save="onSave"
    @delete="onDelete"
    />
  </div>

  <!-- 时间超时 -->
  <TimeOutView v-if="timeFlag"/>
</template>

<script lang="ts" setup>
import HeaderView from '@/components/Header/IndexView.vue'
import TimeOutView from '@/components/TimeOut/IndexView.vue'
import { useRouter, useRoute } from 'vue-router'
import { areaList } from '@vant/area-data'
import { AddAddressFnc, AddressDetailFnc, EditAddressFnc, DeleteAddressFnc } from '@/api/address'
import { AddAddressType } from '@/type/address'

import { ref, onActivated, onMounted } from 'vue'
import { showToast } from 'vant'
const timeFlag = ref(false) // 请求超时 显示界面
const route = useRoute()
const router = useRouter()
const addressDetail = ref<any>({}) // 修改地址 获得对应地址详情
const flag = ref(false) // 条件为true的时候才会进入到onActived生命周期中

// 修改地址 获得对应地址详情
const init = async () => {
  if (route.query.type === 'edit') {
    const res = await AddressDetailFnc(route.query.id).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') timeFlag.value = true
    })

    try {
      if (res?.status === 200) {
        flag.value = true
        addressDetail.value = {
          id: res.data.id,
          name: res.data.name,
          tel: res.data.phone,
          addressDetail: res.data.address.split('-')[0],
          areaCode: res.data.address.split('-')[1],
          isDefault: res.data.is_default === 1
        }
      }
    } catch (error) {
      console.log(error)
    }
  }
}

onMounted(() => { init() })

// 新增地址 或 修改地址 或 公共弹框信息
const publicMsg = (status: number | undefined, msg: string) => {
  try {
    if (status === 201 || status === 204) {
      showToast({
        type: 'success',
        message: msg,
        duration: 1500,
        forbidClick: true,
        onClose: () => {
          router.push('/address')
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}

// 新增地址 或 修改地址
const onSave = async (item: AddAddressType) => {
  const data = {
    name: item.name,
    phone: item.tel,
    province: item.province,
    city: item.city,
    county: item.county,
    address: item.addressDetail + '-' + item.areaCode,
    is_default: item.isDefault ? 1 : 0
  }
  if (route.query.type === 'add') {
    const res = await AddAddressFnc(data).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
      }
    })
    publicMsg(res?.status, '添加成功')
  } else {
    const res = await EditAddressFnc(addressDetail.value.id, data).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
      }
    })
    publicMsg(res?.status, '修改成功')
  }
}

// 删除地址
const onDelete = async (item: {id: number}) => {
  const res = await DeleteAddressFnc(item.id).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
    }
  })

  try {
    publicMsg(res?.status, '删除成功')
  } catch (error) {
    console.log(error)
  }
}

// onMounted 和 onActived两个生命周期会同时触发 解决办法, 只使用onActived函数
onActivated(() => {
  if (route.query.type === 'add') {
    addressDetail.value = {}
  }
  if (flag.value === false) { // 如果flag为false, 那就说明用户首次进入的是新增页面, 那他进入修改页面就应该重新获取数据
    init()
  }
  if (flag.value && addressDetail.value.id !== parseInt(route.query.id)) { // 如果flag为true 并且产品ID不一样，则需要更新产品信息
    init()
  }
})

</script>

<script lang="ts">
export default {
  name: 'editAddressView'
}
</script>

<style lang="scss" scoped>
.address{
  margin-top: 50px;
}
</style>
